<!DOCTYPE HTML>
<html>
    <head>
        <meta charset="utf-8"/>
        <title>使用DataTransfer对象</title>
        <meta name="auther" content="wangjiale"/>
        <style>
            #src>*{float:left;}
            #target,#src>img{border:thin solid black; padding:2px; margin:4px;}
            #target{width:200px; height:200px; text-align:center; display:table;}
            #target>p{display:table-cell; vertical-align:middle;}
            #target>img{margin:1px;}
            img.dragged{background-color:lightgrey;}
        </style>
    </head>
    <body>
        <div id="src">
            <img draggable="true" id="banana" src="images/banana.png" alt="banana"/>
            <img draggable="true" id="apple" src="images/apple.png" alt="apple"/>
            <img draggable="true" id="cherries" src="images/cherries.png" alt="cherries"/>
            <div id="target">
                <p id="msg">Drop Here</p>
            </div>
        </div>
        <script>
            var src=document.getElementById("src");
            var target=document.getElementById("target");
            var msg=document.getElementById("msg");

            //创建释放区域
            target.ondragenter=handleDrag;
            target.ondragover=handleDrag;
            function handleDrag(e){
                e.preventDefault();
            }

            
            src.ondragstart=function(e){
                e.dataTransfer.setData("Text",e.target.id);
                e.target.classList.add("dragged");
            }
            src.ondragend=function(e){
                var elems=document.querySelectorAll(".dragged");
                for(var i=0; i<elems.length; i++){
                    elems[i].classList.remove("dragged");
                }
            }

            target.ondrop=function(e){
                var droppedID=e.dataTransfer.getData("Text");
                var newElem=document.getElementById(droppedID).cloneNode(false);
                /* cloneNode(deep),deep设置为 true，如果您需要克隆节点及其属性，以及后代.
                deep设置为 false，如果您只需要克隆节点及其后代 */
                target.innerHTML="";
                target.appendChild(newElem);
                e.preventDefault();
            }

        </script>
    </body>
</html>